<!--
 * @Description: 考核设置
 * @Author: Boide
 * @Date: 2022-02-18 11:10:44
 * @LastEditors: guiyi@hongyi.tech
 * @LastEditTime: 2022-02-19 17:55:33
-->
<template>
  <el-card class="box-card">
    <el-table v-loading="listLoading" :data="dataList" stripe border row-key="id">
      <el-table-column label="序号" align="center" type="index" width="50" />
      <el-table-column label="名称" align="center">
        <template slot-scope="{row}">
          <span>{{examType[row.examType]}}</span>
        </template>
      </el-table-column>
      <el-table-column label="规则" align="center" prop="examRule" />
      <el-table-column label="考核时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.beginTime | parseTime('{y}-{m}-{d}') }} - {{ row.endTime | parseTime('{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发布状态" align="center">
        <template slot-scope="{row}">
          <span v-if="row.publishState===1">已发布</span>
          <span v-else>未发布</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button v-has-permi="['/wx/menu/pushCustomMenu']" type="text" @click="handleState(row)">
            <span v-if="row.publishState===1">取消发布</span>
            <span v-else>发布</span>
          </el-button>
          <el-button v-has-permi="['/wx/menu/postDelWxTag']" type="text" @click="handleUpdate(row, true)">查看详情</el-button>
          <el-button v-if="row.publishState!==1" v-has-permi="['/wx/menu/postUpdateWxTag']" type="text" @click="handleUpdate(row, false)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜单 -->
    <el-dialog :title="`编辑${examType[formModel.examType]}规则`" :visible.sync="formVisible" width="600px" append-to-body>
      <el-form ref="formModel" :model="formModel" :rules="formModelRules" label-width="85px">
        <el-form-item label="考核时间:" prop="dateTime">
          <el-date-picker
            :readonly="editShow"
            v-model="formModel.dateTime"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            >
          </el-date-picker>
        </el-form-item>
        <el-form-item v-if="formModel.examType==3" label="赛事安排:" prop="examPlan">
          <el-input :readonly="editShow" v-model.trim="formModel.examPlan" type="textarea" :autosize="{ minRows: 4, maxRows: 6}"
            clearable placeholder="请输入赛事安排" maxlength="500" />
        </el-form-item>
        <el-form-item label="规则内容:" prop="examRule">
          <el-input :readonly="editShow" v-model.trim="formModel.examRule" type="textarea" :autosize="{ minRows: 4, maxRows: 6}"
            clearable placeholder="请输入规则内容" maxlength="500" />
        </el-form-item>
        <el-form-item v-if="formModel.examType==3" label="参赛地点:" prop="examPlace">
          <div class="address">
            <div class="address-item" v-for="(item, i) in examAddress" :key="i">
              <el-select :readonly="editShow" class="mr10" style="width: 160px;" v-model="item.area" placeholder="请选择">
                <el-option label="华东地区" :value="1"></el-option>
                <el-option label="华南地区" :value="2"></el-option>
                <el-option label="华西地区" :value="3"></el-option>
                <el-option label="华北地区" :value="4"></el-option>
                <el-option label="华中地区" :value="5"></el-option>
              </el-select>
              <el-input :readonly="editShow" class="mr10" v-model.trim="item.address" clearable placeholder="请输入详细地址" maxlength="100" />
              <div class="btn" v-if="!editShow">
                <el-button v-if="i!==examAddress.length-1" icon="el-icon-close" @click="delAddress(i)"></el-button>
                <el-button v-if="i===examAddress.length-1" icon="el-icon-plus" type="primary" @click="addAddress"></el-button>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item v-if="[5, 6, 7].includes(formModel.examType)" label="展示图片:" prop="imageUrl">
          <upload-img :disabled="editShow" v-model="formModel.imageUrl" />
        </el-form-item>
        <el-form-item v-if="[5, 6, 7].includes(formModel.examType)" :label="`跳转链接:`" prop="linkUrl">
          <el-input :readonly="editShow" v-model.trim="formModel.url" clearable placeholder="请输入跳转网页链接" maxlength="200" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible=!formVisible;reset;">取 消</el-button>
        <el-button v-if="!editShow" :loading="submitLoading" type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import { assessmentSettingsList, assessmentSettingsUpdate } from '@/api/skinDisease/collocate/assess'

export default {
  name: "index",
  data () {
    const validatorDateTime = (_, value, callback) => {
      if (!value || !value.length) {
        callback(new Error('请选择考核时间'));
      } else {
        callback();
      }
    }
    const validatorExamPlace = (_, value, callback) => {
      for (let i = 0; i < this.examAddress.length; i++) {
        const o = this.examAddress[i];
        if (!o.area||!o.address) {
          callback(new Error('请完善当前以及之前的地区,详细地址'));
        }
      }
      callback();
    }
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      examType: {
        1: '首页',
        2: '知识考核',
        3: '实战比拼',
        4: '案例竞赛',
        5: '决赛前',
        6: '决赛中',
        7: '决赛后'
      },
      dataList: [],
      listLoading: false,
      // 新增/编辑用户
      editShow: false,
      formVisible: false,
      submitLoading: false,
      examAddress: [{}],
      formModel: {},
      formModelRules: {
        dateTime: [
          { required: true, validator: validatorDateTime, trigger: "blur" }
        ],
        examRule: [
          { required: true, message: "请输入规则内容", trigger: "blur" }
        ],
        examPlan: [
          { required: true, message: "请输入赛事安排", trigger: "blur" }
        ],
        examPlace: [
          { required: true, validator: validatorExamPlace, trigger: "blur" }
        ],
      }
    }
  },
  methods: {
    addAddress() {
      if (this.examAddress.length>=5) {
        this.$message.warning('参赛地点最多设置5个')
        return
      }
      for (let i = 0; i < this.examAddress.length; i++) {
        const o = this.examAddress[i];
        if (!o.area||!o.address) {
          this.$message.warning('请将当前以及之前的地区,详细地址完善后再新增下一个')
          return
        }
      }
      this.examAddress.push({})
    },
    delAddress(i) {
      this.examAddress.splice(i, 1)
    },
    // 搜索列表
    handleQuery () {
      this.listLoading = true
      assessmentSettingsList().then(res => {
        this.dataList = res.data
        this.listLoading = false
      }).catch(err => {
        if (err.code === -103) {
          this.$router.push('/403')
        }
        this.listLoading = false
      })
    },
    // 发布/取消发布
    handleState({id, publishState}) {
      this.$confirm(`请确认是否要${publishState===1?'发布':'取消发布'}该规则?`, { type: 'warning' }).then(async () => {
        try {
          await assessmentSettingsUpdate({ id, publishState: publishState===1?0:1})
          this.$message.success(`${publishState===1?'取消':'发布'}成功`)
          this.handleQuery()
        } catch (error) {
          console.log(error)
        }
      })
    },
    // 编辑弹窗
    handleUpdate (row, editShow) {
      this.reset()
      const { examType, beginTime, endTime, examPlace } = row
      console.log(examPlace)
      if (examType==3&&examPlace) this.examAddress = JSON.parse(examPlace)
      console.log(this.examAddress)
      this.formModel = {
        ...row,
        dateTime: [beginTime, endTime]
      }
      this.editShow = editShow
      this.formVisible = !this.formVisible
    },
    // 新增/编辑提交
    submitForm () {
      this.submitLoading = true
      this.$refs["formModel"].validate(async valid => {
        console.log(valid)
        if (valid) {
          let params = {...this.formModel}
          params.beginTime = params.dateTime[0]
          params.endTime = params.dateTime[1]
          if (params.examType==3) params.examPlace = JSON.stringify(this.examAddress)
          delete params.dateTime
          try {
            await assessmentSettingsUpdate(params)
            this.$message.success('修改成功')
            this.handleQuery()
            this.formVisible = !this.formVisible
            this.submitLoading = false
          } catch (error) {
            console.log(error)
            this.submitLoading = false
          }
        } else {
          this.submitLoading = false
        }
      })
    },
    // 表单重置
    reset () {
      this.formModel = {
        id: '',
        name: ''
      }
      this.resetForm("formModel")
    },
  },
  mounted () {
    this.handleQuery()
  },
}
</script>

<style lang="scss" scoped>
.address{
  .address-item{
    display: flex;
    &:not(:last-child) {
      margin-bottom: 10px;
    }
    .btn{
      flex-shrink: 0;
      width: 44px;
      height: 32px;
    }
  }
}
</style>
